package hivemq.service.impl;

import cn.hutool.json.JSONObject;
import com.atguigu.springcloud.config.Result;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt3.Mqtt3BlockingClient;
import com.hivemq.client.mqtt.mqtt3.Mqtt3Client;
import hivemq.service.ProducerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @Author zhenyu
 *
 * @desc @Date 2022/10/11 14:43 @Version 1.0
 */
@Component
@Slf4j
public class ProducerServiceImpl implements ProducerService {

  @Value("${mqtt.server.url}")
  private String url;

  @Value("${mqtt.server.port}")
  private int port;

  @Override
  public Result<Object> send(String topic, String message) {

    Mqtt3BlockingClient client =
        Mqtt3Client.builder()
            .identifier(UUID.randomUUID().toString())
            .serverHost(url)
            .serverPort(port)
            .buildBlocking();

    client.connect();

    log.info("MQTT连接成功");

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("message", message);
    String jsonString = jsonObject.toJSONString(0);

    try {

      // 发送消息
      client.toBlocking().publishWith().topic(topic).payload(jsonString.getBytes()).qos(MqttQos.AT_LEAST_ONCE).send();
      log.info("消息发送成功 topic：" + topic + "  payload：" + message);

    } catch (Exception e) {
      e.printStackTrace();
      client.disconnect();
      log.info("MQTT连接关闭");
      return Result.fail(e.getMessage());
    }finally{
      log.info("MQTT连接关闭");
    }
    return Result.success(jsonObject);
  }
}
